package xan.tm.digital.common.exception;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xan.tm.digital.common.entity.BaseResponse;
import xan.tm.digital.common.enums.ErrorCodeEnum;
import xan.tm.digital.common.utils.ResultUtil;

import java.util.stream.Collectors;

/**
 * @author: renwq
 * @date: 2025/9/12 10:36
 * @sesc: 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> handleValidationException(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.error("参数校验异常: {}", errorMessage);
        return ResultUtil.error(ErrorCodeEnum.PARAMS_ERROR, errorMessage);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponse<?> handleConstraintViolationException(ConstraintViolationException ex) {
        String errorMessage = ex.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        log.error("参数校验异常: {}", errorMessage);
        return ResultUtil.error(ErrorCodeEnum.PARAMS_ERROR, errorMessage);
    }
}
